package com.tfjybj.itoo.exam.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.tenancy.TenancyContext;
import com.dmsdbj.itoo.tool.tojson.JacksonJsonUntil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.ManyThread.TotalScore;
import com.tfjybj.itoo.exam.entity.*;
import com.tfjybj.itoo.exam.model.*;
import com.tfjybj.itoo.exam.provider.dao.JudgeTaskDao;
import com.tfjybj.itoo.exam.provider.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * JudgeTaskService接口实现类
 * ${base}表
 *
 * @author 任晓帅
 * @version 2.0.0
 * @since 2.0.0 2018-11-15 19:40:28
 */
@Service("judgeTaskService")
@Slf4j
public class JudgeTaskServiceImpl extends BaseServicePlusImpl<JudgeTaskDao, JudgeTaskEntity>  implements JudgeTaskService {

    //region 模板生成
    @Resource
    private JudgeTaskDao judgeTaskDao;

    @Resource
    private PaperRecordService paperRecordService;

    @Resource
    private StudentScoreDetailService studentScoreDetailService;

    @Resource
    private CourseScheduleService courseScheduleService;

    @Resource
    private StudentScoreService studentScoreService;

    @Resource
    private QuestionService questionService;
    @Resource
    private StaffService staffService;

    @Resource
    private JudgeBussinessQuestionService judgeBussinessQuestionService;

    @Resource
    private ExaminationService examinationService;

    @Resource
    private ExamineeService examineeService;

    @Resource
    private QuestionTypeService questionTypeService;

    @Override
    public PageInfo<JudgeTaskEntity> queryByLikeTeachclassName(String teachclassName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(judgeTaskDao.queryLikeTeachclassName(teachclassName));
    }


    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    /**
     * 根据实体内容进行查询
     *
     * @param judgeTaskModelNorequired
     * @return * @author 侯旭日
     * @since 2.0.0 2018-11-16 19:48:26
     */
    @Override
    public List<JudgeTaskModelResult> queryAllByModel(JudgeTaskModelNorequired judgeTaskModelNorequired) {
//        PaperOnlineRecordModel paperOnlineRecordModel = new PaperOnlineRecordModel();
//        automaticJudge(paperOnlineRecordModel);

        //当前登录人ID
        judgeTaskModelNorequired.setTeacherId(TenancyContext.UserID.get());
        List<JudgeTaskModelResult> taskModelResultList = judgeTaskDao.queryAllByModel(judgeTaskModelNorequired);

        for (JudgeTaskModelResult judgeTaskModel : taskModelResultList) {
            //通过考试ID，班级ID，题型ID判断判分是否已经结束
            judgeTaskModel.setIsJudge(judgeTaskDao.queryJudgeSituation(judgeTaskModel.getExaminationId(), judgeTaskModel.getTemplateDetailsId(), judgeTaskModel.getTeachclassId()));
            //通过考试ID，班级ID，题型ID判断汇总是否已经结束
            judgeTaskModel.setIsTotal(judgeTaskDao.queryTotalSituation(judgeTaskModel.getExaminationId(), judgeTaskModel.getTemplateDetailsId(), judgeTaskModel.getTeachclassId()));
        }
        log.info("查询判分列表成功！");
        return taskModelResultList;
    }

    /**
     * 绑定试卷名称下拉
     *
     * @return * @author 侯旭日
     * @since 2.0.0 2018-11-18 19:48:26
     */
    @Override
    public List<JudgeTaskModelResult> queryDistinctExam() {
        //得到当前登录人ID
        return judgeTaskDao.queryDistinctExam(TenancyContext.UserID.get());
    }

    /**
     * 绑定大题号下拉
     *
     * @return * @author 侯旭日
     * @since 2.0.0 2018-11-18 19:48:26
     */
    @Override
    public List<JudgeTaskModelResult> queryDistinctBigQues() {
        //得到当前登录人ID
        return judgeTaskDao.queryDistinctBigQues(TenancyContext.UserID.get());
    }

    /**
     * 绑定班级下拉
     *
     * @return * @author 侯旭日
     * @since 2.0.0 2018-11-18 19:48:26
     */
    @Override
    public List<JudgeTaskModelResult> queryDistinctClass() {
        //得到当前登录人ID
        return judgeTaskDao.queryDistinctClass(TenancyContext.UserID.get());
    }


    /**
     * 根据考试Id、题型Id、班级Id查询所有答题记录
     *
     * @param examId         考试Id
     * @param questionTypeId 题型Id
     * @param examClassId    班级Id
     * @return 返回值
     * @author 侯旭日
     * @since 2.0.0 2018-11-23 19:48:2
     */
    @Override
    public List<PaperRecordModel> queryJudgeQues(String examId, String questionTypeId, String examClassId) {
        return judgeTaskDao.queryJudgeQues(examId, questionTypeId, examClassId);
    }

    /**
     * 根据考试Id、题型Id、班级Id查询所有未判分总数
     *
     * @param examId         考试ID
     * @param questionTypeId
     * @param examClassId
     * @return
     * @author 侯旭日
     * @since 2.0.0 2018-11-15 19:48:26
     */
    @Override
    public Integer queryJudgeSituation(String examId, String questionTypeId, String examClassId) {
        return judgeTaskDao.queryJudgeSituation(examId, questionTypeId, examClassId);
    }

    /**
     * 更新每小题分数
     *
     * @param id
     * @param score
     * @return
     * @author 侯旭日
     * @since 2.0.0 2018-11-23 19:48:2
     */
    @Override
    public boolean updateManualJudge(String id, double score) {
        //准备更新数据
        PaperRecordEntity paperRecordEntity = new PaperRecordEntity();
        paperRecordEntity.setId(id);
        //0未判 ，1 已判 ，2 已汇总
        paperRecordEntity.setMarkStatus(1);
        //得到当前登录人ID
//        paperRecordEntity.setMarkUser("002");
        paperRecordEntity.setScore(score);
        return paperRecordService.updateManualJudge(paperRecordEntity) == 1;
    }

    /**
     * 根据考试Id、题型Id、班级Id汇总每个学生的题型分数
     *
     * @param examId         考试Id
     * @param questionTypeId 题型Id
     * @param examClassId    班级Id
     * @return
     * @author 程金鹏
     * @since 2.0.0 2019年6月16日18:23:33
     */
    @Transactional(rollbackOn = Exception.class)
    @Override
    public boolean queryEachStuScore(String examId, String questionTypeId, String examClassId) {
        //region 方法说明
        /*1、分数汇总包括混合题型和非混合题型
        * 2、操作步骤：
        *   1）获取根据考试id，题型id，班级id，（其中题型id和班级id可以为空）查询每个学生的已经判分的“非混合题”答题记录，并在paper_record 表中，将MarkStatus字段改成汇总状态
        *   2）获取根据考试id，题型id，班级id，（其中题型id和班级id可以为空）查询每个学生的已经判分的“混合题”答题记录，并在paper_record 表中，将MarkStatus字段改成汇总状态
        *   3）根据考试id，计算每个学生每张卷的总分，并查询本考试id对应的考试科目
        *   4）向学生总分表插入数据，分为第一次汇总插入还是第二次汇总后 的更新
        *   */
        //endregion

        //region 1）获取根据考试id，题型id，班级id，（其中题型id和班级id可以为空）查询每个学生的已经判分的“非混合题”答题记录，并在paper_record 表中，将MarkStatus字段改成汇总状态

        List<PaperRecordModel> paperRecordModels = judgeTaskDao.queryJudgeQues(examId, questionTypeId, examClassId);
        log.info("有{}条已判分非父子题数据进行汇总", paperRecordModels.size());
        //在paperrecorde表中更新汇总状态MarkStatus字段
        inserStuScoreDetail( paperRecordModels, examId);
        //endregion

        //region 2）获取根据考试id，题型id，班级id，（其中题型id和班级id可以为空）查询每个学生的已经判分的“混合题”答题记录，并在paper_record 表中，将MarkStatus字段改成汇总状态
        List<PaperRecordModel> paperRecordModels1 = judgeTaskDao.queryJudgeQuesBlend(examId, questionTypeId, examClassId);
        log.info("有{}条已判分父子题数据进行汇总", paperRecordModels.size());
//        在paperrecorde表中更新汇总状态MarkStatus字段
        inserStuScoreDetail( paperRecordModels1, examId);
        //endregion

        //region 3）根据考试id，计算每个学生每张卷的总分，并查询本考试id对应的考试科目
        //根据考试id，计算每个学生每张卷的总分
        List<JudgeTotalScoreModel> judgeTotalScoreModels = judgeTaskDao.queryEachPaperScore(examId, examClassId);
        //调用接口查询课程name
        String courseName = "找不到科目名称！";

//        如果没有根据考试id，计算每个学生每张卷的总分，则退出程序
        if (judgeTotalScoreModels == null || judgeTotalScoreModels.size() <= 0) {
            log.warn("答题记录表中没有该场考试信息,或者模板已经被删除，或者是paperrecord中没有学生记录，考试ID为：{}", examId);
            return false;
        } else { //如果根据考试id，计算出每个学生每张卷的总分，则查询出来本此考试id的考试科目
            JudgeTotalScoreModel judgeTotalScoreModel = judgeTotalScoreModels.get(0);
            if (judgeTotalScoreModel != null) {
                courseName = courseScheduleService.findByCourseId(judgeTotalScoreModel.getCourseId());
            }
        }
        //endregion

        //region 4）向学生总分表插入数据，分为第一次汇总插入还是第二次汇总后 的更新
        //向学生成绩表插入数据
        for (JudgeTotalScoreModel judgeTotalScoreModel : judgeTotalScoreModels) {
            //判断成绩详情表是否有该考生数据，如果有说明已经汇总过一次，如果没有说明第一次汇总，每判完一道大题就会汇总一次
            //通过考生ID和考试ID查询是否已经汇总过该场考试的分数
            StudentScoreEntity stuScoreEntity = new StudentScoreEntity();
            stuScoreEntity.setExamineeId(judgeTotalScoreModel.getExamineeId());
            stuScoreEntity.setExaminationId(examId);
            Wrapper<StudentScoreEntity> wrapper = new QueryWrapper(stuScoreEntity);
            List<StudentScoreEntity> studentScoreEntities = studentScoreService.list(wrapper);
            //没有汇总过添加到学生成绩表
            if (CollectionUtils.isEmpty(studentScoreEntities)) {
                StudentScoreEntity studentScoreEntity = new StudentScoreEntity();
                studentScoreEntity.setStudentCode(judgeTotalScoreModel.getStudentCode());
                studentScoreEntity.setStudentName(judgeTotalScoreModel.getExamineeName());
                studentScoreEntity.setStudentScore(judgeTotalScoreModel.getTotalScore());
                studentScoreEntity.setExamineeId(judgeTotalScoreModel.getExamineeId());
                studentScoreEntity.setFullScore(judgeTotalScoreModel.getScore());
                studentScoreEntity.setClassId(judgeTotalScoreModel.getClassId());
                studentScoreEntity.setClassName(judgeTotalScoreModel.getClassName());
                studentScoreEntity.setMajorId(judgeTotalScoreModel.getMajorId());
                studentScoreEntity.setMajorName(judgeTotalScoreModel.getMajorName());
                studentScoreEntity.setCourseId(judgeTotalScoreModel.getCourseId());
                studentScoreEntity.setCourseName(courseName);
                studentScoreEntity.setExaminationId(examId);
                studentScoreEntity.setExamClassifyId(judgeTotalScoreModel.getExamClassifyId());
                studentScoreEntity.setTemplateId(judgeTotalScoreModel.getTemplateId());
                studentScoreEntity.setTemplateName(judgeTotalScoreModel.getTemplateName());
                studentScoreService.save(studentScoreEntity);
            } else {
                StudentScoreEntity studentScoreEntity = new StudentScoreEntity();
                //把现在得分和之前得分加起来
                try {
                    String strScore = judgeTotalScoreModel.getTotalScore();
                    if (!StringUtils.isEmpty(strScore)) {
                        Double score = Double.parseDouble(judgeTotalScoreModel.getTotalScore());
                        studentScoreEntity.setStudentScore(score.toString());
                    } else {
                        log.warn("该场考试，该考生下所有试题都没有判分！！！考试ID：{}考生ID：{}", examId, judgeTotalScoreModel.getExamineeId());
                        studentScoreEntity.setStudentScore("-1");
                    }
                } catch (Exception ex) {
                    log.error("判分汇总：获得的成绩不能转换为数字,成绩为：{}", judgeTotalScoreModel.getTotalScore());
                }
                studentScoreService.update(studentScoreEntity, wrapper);
            }
        }
        //endregion
        return true;
    }

    private void inserStuScoreDetail(List<PaperRecordModel> paperRecordModelist, String examId) {
//        判断paperRecordModelist是否为空
        if (paperRecordModelist != null && paperRecordModelist.size() > 0) {
            List<PaperRecordEntity> paperRecordEntities = new ArrayList<>();
//            遍历paperRecordModelist中的内容
            for (PaperRecordModel paperRecordModel : paperRecordModelist) {
                PaperRecordEntity paperRecordEntity = new PaperRecordEntity();
                paperRecordEntity.setId(paperRecordModel.getId());
                //0未判 ，1 已判 ，2 已汇总
                paperRecordEntity.setMarkStatus(2);
                paperRecordEntities.add(paperRecordEntity);
            }
//            将汇总状态MarkStatus更新到paperrecord表中
            paperRecordService.updateBatchById(paperRecordEntities);
        }
    }

    /**
     * 查询考试名称
     *
     * @return
     * @author 刘梦娇
     * @since 2018-12-12 17:25:30
     */
    @Override
    public List<ExaminationModel> queryExamName() {
        return judgeTaskDao.queryExamName(TenancyContext.UserID.get());
    }

    @Override
    public List<JudgeTaskModelResult> queryQuestionTypeName(String examinationId) {
        return judgeTaskDao.queryQuestionTypeName(examinationId);
    }

    /**
     * 自动判分
     *
     * @param paperOnlineRecordModel
     * @return
     */
    @Override
    public boolean automaticJudge(PaperOnlineRecordModel paperOnlineRecordModel) {
//        paperOnlineRecordModel.setPaperId("1080015508943794220");
//        paperOnlineRecordModel.setQuestionCode("16");
//        paperOnlineRecordModel.setStudentAnswerS("对");
//        paperOnlineRecordModel.setStandardScore(4);
//
//        String[] bbb=new String[5];
//
//        bbb[0]="[{\"explain\":\"\",\"borrowList\":[{\"type\":\"借：\",\"subject\":\"劳务成本\",\"explain\":\"成本\",\"amount\":\"100\",\"itemOrder\":1,\"display\":true},{\"type\":\"借：\",\"subject\":\"衍生工具\",\"explain\":\"提取任意盈余公积\",\"display\":true,\"itemOrder\":2,\"amount\":0}],\"loanList\":[{\"type\":\"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;贷：\",\"subject\":\"衍生工具\",\"explain\":\"存出投资款\",\"amount\":\"100\",\"itemOrder\":1}],\"order\":1}]";
//        bbb[1]="[{\"explain\":\"\",\"borrowList\":[{\"type\":\"借：\",\"subject\":\"递延所得税负债\",\"explain\":\"待处理流动资产损溢\",\"itemOrder\":1,\"amount\":0},{\"type\":\"借：\",\"subject\":\"衍生工具\",\"explain\":\"公允价值变动\",\"itemOrder\":2,\"amount\":0}],\"loanList\":[{\"type\":\"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;贷：\",\"subject\":\"劳务成本\",\"explain\":\"公允价值变动\",\"itemOrder\":1,\"amount\":0},{\"type\":\"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;贷：\",\"subject\":\"被套期工具\",\"explain\":\"任意盈余公积\",\"itemOrder\":2,\"amount\":0}],\"order\":2}]";
//        bbb[4]="[{\"explain\":\"5\",\"borrowList\":[{\"type\":\"借：\",\"subject\":\"劳务成本\",\"explain\":\"失业保险\",\"amount\":\"5\",\"itemOrder\":1}],\"loanList\":[{\"type\":\"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;贷：\",\"subject\":\"劳务成本\",\"explain\":\"失业保险\",\"amount\":\"5\",\"itemOrder\":1}],\"order\":5}]";
//        paperOnlineRecordModel.setStudentAnswerArray(bbb);
        log.info("{}该答题记录开始判分！！！",paperOnlineRecordModel.getPaperRecordId());
        if (StringUtils.isEmpty(paperOnlineRecordModel.getPaperRecordId()) || StringUtils.isEmpty(paperOnlineRecordModel.getQuestionCode()) || StringUtils.isEmpty(paperOnlineRecordModel.getStudentAnswerS()) || paperOnlineRecordModel.getStandardScore() < 0) {
            if (!StringUtils.isEmpty(paperOnlineRecordModel.getQuestionCode()) && "16".equals(paperOnlineRecordModel.getQuestionCode()) && StringUtils.isEmpty(paperOnlineRecordModel.getStudentAnswerS())) {
                log.warn("该考生本业务小题没有做答，答题记录ID:{}", paperOnlineRecordModel.getPaperRecordId());
            } else {
                log.warn("自动判分传递参数不全！\n答题记录ID：{}\n试题类型(0(填空题)、1(单选题)、2(多选题)、6(计算选择题)、9(判断题)、11(简答题)、15(业务选择题)、16(业务题)、17(混合题)、18(计算分析题)、19(填图题)、20(名词解释题))：{}\n学生答案：{}\n标准分数：{}", paperOnlineRecordModel.getPaperRecordId(), paperOnlineRecordModel.getQuestionCode(), paperOnlineRecordModel.getStudentAnswerS(), paperOnlineRecordModel.getStandardScore());
                return false;
            }
        }

        //通过试题ID去答题记录找这道的标准答案和标准分数等信息
        PaperRecordEntity recordEntity = paperRecordService.getById(paperOnlineRecordModel.getPaperRecordId());
        if (recordEntity == null) {
            log.warn("在答题记录表中没有该题，传入试题ID：" + paperOnlineRecordModel.getPaperRecordId());
            return false;
        }
        //默认成绩0分
        recordEntity.setScore(0d);
        paperOnlineRecordModel.setScore(0d);
        //题目及答案信息
        QuestionEntity questionEntity = questionService.getById(recordEntity.getQuestionId());
        List<QuestionEntity> questionEntities;
        //分隔标准答案选项
        if (questionEntity == null) {
            if (paperOnlineRecordModel.getState()) {
                log.info("该答题记录里面QuestionId在题库中没有找到，进行补偿判分！答题记录ID：{}，QuestionID：{}", paperOnlineRecordModel.getPaperRecordId(), recordEntity.getQuestionId());
                questionEntities = questionService.selectNewQuestionById(recordEntity.getQuestionId());
                if (questionEntities == null || questionEntities.size() <= 0) {
                    log.warn("进行补偿判分失败，题库没有找到修改之后的试题，历史题ID为：{}", recordEntity.getQuestionId());
                    return false;
                }
                questionEntity = new QuestionEntity();
                questionEntity.setAnswer(questionEntities.get(0).getAnswer());
                questionEntity.setOptionCount(questionEntities.get(0).getOptionCount());
//
            } else {
                log.warn("该答题记录里面QuestionId在题库中没有找到，答题记录ID：{}，QuestionID：{}", paperOnlineRecordModel.getPaperRecordId(), recordEntity.getQuestionId());
                return false;
            }
        }
        String[] standardOption = questionEntity.getAnswer().split("\\|");
        //分隔学生选项，除业务题以外
        String[] stuOption = null;
        if (!"16".equals(paperOnlineRecordModel.getQuestionCode())) {
            stuOption = paperOnlineRecordModel.getStudentAnswerS().split("\\|");
        }
        //region 单选、多选和业务选择题  判断题按一种类型判分
        if ("1".equals(paperOnlineRecordModel.getQuestionCode()) || "2".equals(paperOnlineRecordModel.getQuestionCode()) || "9".equals(paperOnlineRecordModel.getQuestionCode()) || "15".equals(paperOnlineRecordModel.getQuestionCode())) {
            //标准答案和学生答案进行匹配，得到正确个数和错误个数
            int correctNum = 0;//正确个数用来判断多选题是否漏选
            int errNum = 0;//错误个数用来多选题是否选错
            //学生答案
            for (String aStuOption : stuOption) {
                //这个多选没答
                if ("".equals(aStuOption.trim())) {
                    continue;
                }
                boolean flag = true;
                //标准答案
                for (String str : standardOption) {
                    //需要把前后空格去掉
                    if (str.trim().equals(aStuOption.trim())) {
                        correctNum++;
                        flag = false;
                        break;
                    }
                }
                //只要有一个答错这题就错了
                if (flag) {
                    errNum++;
                    break;
                }
            }
            //学生答案个数和标准答案个数一样，且两个答案交集一样
            if (correctNum == standardOption.length && correctNum == standardOption.length) {
                //不管是单选、多选还是判断题，是全对的情况
                recordEntity.setScore(paperOnlineRecordModel.getStandardScore());
                paperOnlineRecordModel.setScore(paperOnlineRecordModel.getStandardScore());
            } else if (errNum == 0 && correctNum < standardOption.length) {
                //没有选错并且答对个数少于标准答案个数，说明漏选
                if (paperOnlineRecordModel.getMessingPointsScore() < 0) {
                    log.warn("漏选分数传递参数不合法：{}", paperOnlineRecordModel.getMessingPointsScore());
                    return false;
                }
                recordEntity.setScore(paperOnlineRecordModel.getMessingPointsScore());
                paperOnlineRecordModel.setScore(paperOnlineRecordModel.getMessingPointsScore());
            } else {
                //答错情况
                recordEntity.setScore(0d);
                paperOnlineRecordModel.setScore(0d);
            }
            //0：未判分  1：已判分   2：已汇总
            recordEntity.setMarkStatus(1);
//            recordEntity.setMarkUser("002");
            if (paperOnlineRecordModel.getIsUpdate()){
                paperRecordService.updateById(recordEntity);
            }
            log.info("{}判分成功！！！学生答案：{}，标准分数：{}，选项或填空数量：{}", paperOnlineRecordModel.getQuestionCode(), paperOnlineRecordModel.getStudentAnswerS(), paperOnlineRecordModel.getStandardScore(), questionEntity.getOptionCount());
            return true;
        }
        //endregion
        //region 填空题、填图题和计算分析题按一种类型判分
        if ("0".equals(paperOnlineRecordModel.getQuestionCode()) || "19".equals(paperOnlineRecordModel.getQuestionCode()) || "18".equals(paperOnlineRecordModel.getQuestionCode())) {
            int correctNum = 0;//正确个数用来判断答对几个空
            int  errNum = 0;//错误个数用来判断答错几个空

            //学生做答，进行判分，没有做答直接0分
            if (stuOption.length > 0) {
                //判断是否乱序 0：不可乱序   1：可乱序
                if (questionEntity.getIsOutOfOrder() == 0) {
                    for (int i = 0; i < stuOption.length; i++) {
                        //从答案里提取别名
                        String[] alias = standardOption[i].split("@#");
                        for (String strAli : alias) {
                            if (strAli.trim().equals(stuOption[i].trim())) {
                                correctNum++;
                                break;
                            }
                        }
                    }
                } else {
                    //可乱序
                    for (String aStuOption : stuOption) {
                        boolean isTrue = false;
                        for (int j = 0; j < standardOption.length; j++) {
                            if (StringUtils.isEmpty(standardOption[j])) {
                                continue;
                            }
                            //从答案里提取别名
                            String[] alias = standardOption[j].split("@#");
                            for (String strAli : alias) {
                                if (strAli.trim().equals(aStuOption.trim())) {
                                    correctNum++;
                                    isTrue = true;
                                    break;
                                }
                            }
                            //说明这个答案它已经答对了，就不再判断了
                            if (isTrue) {
                                standardOption[j] = "";
                                break;
                            }
                        }
                        if (!isTrue) {
                            errNum++;
                        }
                    }
                }
            }
            recordEntity.setScore(0d);
            paperOnlineRecordModel.setScore(0d);
            if (correctNum > 0) {
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                recordEntity.setScore(Double.parseDouble(decimalFormat.format(paperOnlineRecordModel.getStandardScore() / questionEntity.getOptionCount() * correctNum)));
                paperOnlineRecordModel.setScore(Double.parseDouble(decimalFormat.format(paperOnlineRecordModel.getStandardScore() / questionEntity.getOptionCount() * correctNum)));
            }
            //0：未判分  1：已判分   2：已汇总
            recordEntity.setMarkStatus(1);
            if (paperOnlineRecordModel.getIsUpdate()){
                paperRecordService.updateById(recordEntity);
            }
            log.info("{}判分成功！！！学生答案：{}，标准分数：{}，选项或填空数量：{}", paperOnlineRecordModel.getQuestionCode(), paperOnlineRecordModel.getStudentAnswerS(), paperOnlineRecordModel.getStandardScore(), questionEntity.getOptionCount());
            return true;
        }
        //endregion

        //region 业务题
        if ("16".equals(paperOnlineRecordModel.getQuestionCode())) {
            /**
             * 业务题判分逻辑
             * 第一种（标准判分）：一个小题中多个业务错任意一个空该小题都无分
             * 把该小题下标准答案所有业务的借货排序，把学生答案所有业务借贷排序
             * 一对一比较，错一个都不行
             *
             * 第二种（较严格判分）：一个小题中多个业务中一级科目对给一个空的分，金额对再给一个空的分
             * 注意：多个业务之间可以乱序，业务里面多个借、多个贷之间都可乱序
             * 用标准答案中第一个业务匹配学生答案第一到第N个业务，匹配结果放入Map中
             * 用标准答案中第二、第三...N个业务匹配学生答案第一到第N个业务，匹配结果放入Map中
             * 上两步会有多个Map，标准答案有几个业务就会产生几个Map
             * 把所有Map用一个大Map包起来
             * 分析大Map中每个小Map第一个到第N个的值，取最大的，最大的是他答对的总空数
             * 这道题除以总空数乘他答对的空数就是他的分数
             * 注意：有时候会出现误差，但是可以忽略不计，学生多答一个借或贷，并且一级科目写对，金额算错了，这样这个会给他一分
             * 下一个借或贷他答对了就不会再给分了，这样会差一个空，因为一个空的分数太小了可以忽略不计
             **/

            //里面有多种判分规则，目前二种，第一种是规定，第二种是老师要求
            //转换学生答案
            paperOnlineRecordModel.setStudentAnswerS("");
            for (int i = 0; i < paperOnlineRecordModel.getStudentAnswerArray().length; i++) {
                if (paperOnlineRecordModel.getStudentAnswerArray()[i] == null) {
                    paperOnlineRecordModel.setStudentAnswerS(paperOnlineRecordModel.getStudentAnswerS() + "[{\"explain\":\"1\",\"borrowList\":[{\"type\":\"借：\",\"subject\":\"\",\"explain\":\"\",\"amount\":\"\",\"itemOrder\":1}],\"loanList\":[{\"type\":\"贷：\",\"subject\":\"\",\"explain\":\"\",\"amount\":\"\",\"itemOrder\":1}],\"order\":1}]|");
                    log.info("该考生业务题第{}小题没有做答", i + 1);
                } else {
                    log.info("该考生业务题第{}小题已经做答", i + 1);
                    paperOnlineRecordModel.setStudentAnswerS(paperOnlineRecordModel.getStudentAnswerS() + paperOnlineRecordModel.getStudentAnswerArray()[i] + "|");
                }
            }
            //没有做答
            for (int i = 0; i < questionEntity.getOptionCount() - paperOnlineRecordModel.getStudentAnswerArray().length; i++) {
                paperOnlineRecordModel.setStudentAnswerS(paperOnlineRecordModel.getStudentAnswerS() + "[{\"explain\":\"1\",\"borrowList\":[{\"type\":\"借：\",\"subject\":\"\",\"explain\":\"\",\"amount\":\"\",\"itemOrder\":1}],\"loanList\":[{\"type\":\"贷：\",\"subject\":\"\",\"explain\":\"\",\"amount\":\"\",\"itemOrder\":1}],\"order\":1}]|");
            }
//            if (paperOnlineRecordModel.getStudentAnswerArray().length!=paperOnlineRecordModel.getOptionCount()){
//                log.warn("业务题传入学生答案小题个数与标准答案小题个数不一致！！！答题记录ID：{}，学生答案个数为：{}，标准答案个数为：{}",paperOnlineRecordModel.getPaperId(),paperOnlineRecordModel.getStudentAnswerArray().length,paperOnlineRecordModel.getOptionCount());
//                return false;
//            }
            paperOnlineRecordModel.setStudentAnswerS(paperOnlineRecordModel.getStudentAnswerS().substring(0, paperOnlineRecordModel.getStudentAnswerS().length() - 1));
            String stuAnswer = "[{\"question\":" + paperOnlineRecordModel.getStudentAnswerS().replace("|", "},{\"question\":") + "}]";
//            String stuAnswer = "[{\"question\":" + paperOnlineRecordModel.getStudentAnswerS().replace("|", "},{\"question\":") + "}]";
            List<BussinessStuAllAnswerModel> bussinessStuAllAnswerModels;
            try {
                bussinessStuAllAnswerModels = JacksonJsonUntil.jsonToList(stuAnswer, BussinessStuAllAnswerModel.class);
            } catch (Exception ex) {
                log.error("业务题学生答案转换失败！原因：该题前端传入格式不合法，后端转换失败! 本题ID：" + paperOnlineRecordModel.getPaperRecordId());
                return false;
            }
            //转换标准答案
            List<BussinessAllModel> bussinessAllModels;
            try {
                bussinessAllModels = JacksonJsonUntil.jsonToList(standardOption[0], BussinessAllModel.class);
            } catch (Exception ex) {
                log.error("业务题标准答案转换失败！原因：该题存入库中标准答案不合法! 本题ID：" + paperOnlineRecordModel.getPaperRecordId());
                return false;
            }

            //查询数据库得到用哪种方法判分
            JudgeBussinessQuestionEntity judgeBussinessQuestionEntity = new JudgeBussinessQuestionEntity();
            //所有判分情况是否可用
            judgeBussinessQuestionEntity.setState(1);
            Wrapper<JudgeBussinessQuestionEntity> wrapper = new QueryWrapper(judgeBussinessQuestionEntity);
            List<JudgeBussinessQuestionEntity> list = judgeBussinessQuestionService.list(wrapper);
            //没有设置默认不判分
            if (list == null || list.size() == 0) {
                log.warn("在业务题中没有设置默认判分规则，业务题不会被判分！！！设置判分规则表：te_judge_bussiness_question");
                return false;
            }
            //0表示正常判分
            if (list.get(0).getRuleCode() == 0) {
                //region 第一种，标准判分，借贷和金额错一个都不给分
                boolean flagBool = true;
                //获得每个业务中每个小题
                for (int i = 0; i < bussinessStuAllAnswerModels.size(); i++) {
                    //获得每个小题的每个业务，每个小题中的业务可以乱序，得到学生答案里面的所有借贷
                    List<String> stuAllAnsw = new ArrayList<>();
                    for (int j = 0; j < bussinessStuAllAnswerModels.get(i).getQuestion().size(); j++) {
                        //获得每个业务中的借
                        for (BorrowIssueModel borrowIssueModel : bussinessStuAllAnswerModels.get(i).getQuestion().get(j).getBorrowList()) {
                            //用第i个业务中的借和标准答案所有业务匹配，错一个即为错
                            stuAllAnsw.add(borrowIssueModel.getSubject().trim() + borrowIssueModel.getAmount().trim());
                        }
                        //获得每个业务中的贷
                        for (LoanIssueModel loanIssueModel : bussinessStuAllAnswerModels.get(i).getQuestion().get(j).getLoanList()) {
                            stuAllAnsw.add(loanIssueModel.getSubject().trim() + loanIssueModel.getAmount().trim());
                        }
                    }
                    //得到标准答案里面的所有借贷
                    List<String> standardAllAnsw = new ArrayList<>();
                    for (int j = 0; j < bussinessAllModels.get(i).getBussinessAllList().size(); j++) {
                        //获得每个业务中的借
                        for (BorrowIssueModel borrowIssueModel : bussinessAllModels.get(i).getBussinessAllList().get(j).getBorrowList()) {
                            standardAllAnsw.add(borrowIssueModel.getSubject().trim() + borrowIssueModel.getAmount().trim());
                        }
                        //获得每个业务中的贷
                        for (LoanIssueModel loanIssueModel : bussinessAllModels.get(i).getBussinessAllList().get(j).getLoanList()) {
                            standardAllAnsw.add(loanIssueModel.getSubject().trim() + loanIssueModel.getAmount().trim());
                        }
                    }
                    //对所有借贷排序
                    Collections.sort(stuAllAnsw);
                    Collections.sort(standardAllAnsw);
                    //给每个小题判分，有一个不一样就0分
                    //先判断数量，数量不一样直接0
                    boolean flag = true;
                    if (stuAllAnsw.size() == standardAllAnsw.size()) {
                        for (int j = 0; j < stuAllAnsw.size(); j++) {
                            if (!stuAllAnsw.get(j).equals(standardAllAnsw.get(j))) {
                                flag = false;
                                flagBool = false;
                                break;
                            }
                        }
                        if (flag) {
                            recordEntity.setScore(paperOnlineRecordModel.getStandardScore());
                            paperOnlineRecordModel.setScore(paperOnlineRecordModel.getStandardScore());
                        } else {
                            recordEntity.setScore(0d);
                            paperOnlineRecordModel.setScore(0d);
                            flagBool = false;
                            break;
                        }
                    } else {
                        recordEntity.setScore(0d);
                        paperOnlineRecordModel.setScore(0d);
                        flagBool = false;
                        break;
                    }
                }
                if (flagBool) {
                    recordEntity.setScore(paperOnlineRecordModel.getStandardScore());
                    paperOnlineRecordModel.setScore(paperOnlineRecordModel.getStandardScore());
                } else {
                    recordEntity.setScore(0d);
                    paperOnlineRecordModel.setScore(0d);
                }
                recordEntity.setMarkStatus(1);
                if (paperOnlineRecordModel.getIsUpdate()){
                    paperRecordService.updateById(recordEntity);
                }
                log.info("{}判分成功！！！学生答案：{}，标准分数：{}，选项或填空数量：{}", paperOnlineRecordModel.getQuestionCode(), paperOnlineRecordModel.getStudentAnswerS(), paperOnlineRecordModel.getStandardScore(), questionEntity.getOptionCount());
                return true;
                //endregion
            } else if (list.get(0).getRuleCode() == 1) {
                //1表示较严格判分
                //region 第二种情况：较严格判分   一级科目答对给一个空的分，金额答对给一个空的分
                //获得每个小题答对的空数
                int stuTotalNum = 0;
                int standTotalNum = 0;
                //获得标准答案每个业务中每个小题
                for (int i = 0; i < bussinessAllModels.size(); i++) {
                    //获得每个小题的每个业务，每个小题中的业务可以乱序
                    HashMap<Integer, HashMap> mm = new HashMap<>();
                    //统计正确答案总空数
                    int answerCnt = 0;
                    for (int j = 0; j < bussinessAllModels.get(i).getBussinessAllList().size(); j++) {
                        List<String> standardAllAnswBorr = new ArrayList<>();
                        List<String> standardAllAnswLoan = new ArrayList<>();
                        HashMap<Integer, Integer> m = new HashMap<>();
                        //获得标准答案每个业务中的借
                        for (BorrowIssueModel borrowIssueModel : bussinessAllModels.get(i).getBussinessAllList().get(j).getBorrowList()) {
                            //把标准答案中借存起来
                            standardAllAnswBorr.add(borrowIssueModel.getSubject().trim() + "|" + borrowIssueModel.getAmount());
                            answerCnt += 2;
                        }
                        //获得标准答案每个业务中的贷
                        for (LoanIssueModel loanIssueModel : bussinessAllModels.get(i).getBussinessAllList().get(j).getLoanList()) {
                            //把标准答案中贷存起来
                            standardAllAnswLoan.add(loanIssueModel.getSubject().trim() + "|" + loanIssueModel.getAmount());
                            answerCnt += 2;
                        }
                        //获得学生答案每个业务
                        if (i + 1 <= bussinessStuAllAnswerModels.size()) {
                            for (int k = 0; k < bussinessStuAllAnswerModels.get(i).getQuestion().size(); k++) {
                                List<String> stuAllAnswBorr = new ArrayList<>();
                                List<String> stuAllAnswLoan = new ArrayList<>();
                                //获得学生答案每个业务中的借
                                for (BorrowIssueModel borrowIssueModel : bussinessStuAllAnswerModels.get(i).getQuestion().get(k).getBorrowList()) {
                                    //把学生答案借存起来
//                                if (borrowIssueModel.getSubject()==null){
//                                    borrowIssueModel.setSubject("");
//                                }
//                                if (borrowIssueModel.getAmount()==null){
//                                    borrowIssueModel.setAmount("");
//                                }
                                    stuAllAnswBorr.add(borrowIssueModel.getSubject().trim() + "|" + borrowIssueModel.getAmount());
                                }
                                //获得学生答案每个业务中的贷
                                for (LoanIssueModel loanIssueModel : bussinessStuAllAnswerModels.get(i).getQuestion().get(k).getLoanList()) {
                                    //把学生答案贷存起来
                                    stuAllAnswLoan.add(loanIssueModel.getSubject().trim() + "|" + loanIssueModel.getAmount());
                                }
                                //因为可以乱序，所以对答案进行排序   ——借
                                Collections.sort(standardAllAnswBorr);
                                Collections.sort(stuAllAnswBorr);
                                //——贷
                                Collections.sort(standardAllAnswLoan);
                                Collections.sort(stuAllAnswLoan);
                                //统计所有借中对的个数
                                int cnt = totalNum(standardAllAnswBorr, stuAllAnswBorr);
                                //统计所有贷中对的个数
                                cnt += totalNum(standardAllAnswLoan, stuAllAnswLoan);
                                //把对应关系放入Map中
                                m.put(k, cnt);

                            }
                        }
                        //每个小题对应关系放入Map中
                        mm.put(j, m);
                    }
                    //开始判分
                    int h = mm.get(0).size();
                    int mCnt = mm.size();
                    //统计该小题下对几个空
                    int cnt = 0;
                    for (int j = 0; j < h; j++) {
                        //存入该小题下的每个业务题对几个空数
                        int max = 0;
                        int log = -1;
                        for (int k = 0; k < mCnt; k++) {
                            HashMap hs;
                            if (mm.containsKey(k)) {
                                hs = mm.get(k);
                            } else {
                                continue;
                            }
                            //获得答对最多的业务，并把下标保存下来
                            if (Integer.parseInt(hs.get(j).toString()) > max) {
                                max = Integer.parseInt(hs.get(j).toString());
                                log = k;
                            }
                        }
                        //匹配成功的记录删除
                        if (log != -1) {
                            mm.remove(log);
                        }
                        cnt += max;
                    }
                    stuTotalNum += cnt;
                    standTotalNum += answerCnt;
                }
                //说明这道题满分
                if (stuTotalNum == standTotalNum) {
                    recordEntity.setScore(paperOnlineRecordModel.getStandardScore());
                    paperOnlineRecordModel.setScore(paperOnlineRecordModel.getStandardScore());
                } else {
                    //对一部分
                    double num = paperOnlineRecordModel.getStandardScore() / standTotalNum * stuTotalNum;
                    DecimalFormat df = new DecimalFormat("#.00");
                    recordEntity.setScore(Double.parseDouble(df.format(num)));
                    paperOnlineRecordModel.setScore(Double.parseDouble(df.format(num)));
                }
                //0：未判分  1：已判分   2：已汇总
                recordEntity.setMarkStatus(1);
//                    recordEntity.setMarkUser("002");
                log.info("{}判分成功！！！学生答案：{}，标准分数：{}，选项或填空数量：{}", paperOnlineRecordModel.getQuestionCode(), paperOnlineRecordModel.getStudentAnswerS(), paperOnlineRecordModel.getStandardScore(), questionEntity.getOptionCount());
                if (paperOnlineRecordModel.getIsUpdate()){
                    paperRecordService.updateById(recordEntity);
                }
                //endregion
                return true;
            }
        }
        //endregion
        log.warn("传入判分题型名称与规定的题型名称不符合（0(填空题)、1(单选题)、2(多选题)、6(计算选择题)、9(判断题)、11(简答题)、15(业务选择题)、16(业务题)、17(混合题)、18(计算分析题)、19(填图题)、20(名词解释题)），题型名称为：{}", paperOnlineRecordModel.getQuestionCode());
        return false;
    }

    private int totalNum(List<String> standardAllAnswBorr, List<String> stuAllAnswBorr) {
        int cnt = 0;
        for (String standAns : standardAllAnswBorr) {
            String[] splitStandAns = standAns.split("\\|");
            for (int l = 0; l < stuAllAnswBorr.size(); l++) {
                if (stuAllAnswBorr.get(l).isEmpty()) {
                    continue;
                }
                String[] splitStuAns = stuAllAnswBorr.get(l).split("\\|");
                //匹配一级科目
                if (splitStuAns.length > 0 && splitStandAns[0].equals(splitStuAns[0])) {
                    cnt++;
                    stuAllAnswBorr.set(l, "");
                    //匹配金额
                    if (splitStuAns.length == 2 && splitStandAns[1].trim().equals(splitStuAns[1].trim())) {
                        cnt++;
                        break;
                    }
                    break;
                }
            }
        }
        return cnt;
    }


    @Override
    public List<JudgeTaskModelResult> queryAllByJudgeTask(JudgeTaskModelNorequired model) {
        List<JudgeTaskModelResult> judgeTaskModelResults = judgeTaskDao.queryAllByModel(model);
        for (JudgeTaskModelResult judgeTaskModelResult : judgeTaskModelResults) {
            judgeTaskModelResult.setTeacherName(staffService.getById(judgeTaskModelResult.getTeacherId()).getName());

        }
        return judgeTaskModelResults;
    }


    @Override
    public PageInfo<JudgeTaskModelResult> queryLikeClassName(String teachclassName, String operator, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<JudgeTaskModelResult> judgeTaskModelResultList = judgeTaskDao.queryLikeClassName(teachclassName, operator);
        return new PageInfo<>(judgeTaskModelResultList);
    }


    /**
     * 修改手动判分任务的批卷人
     *
     * @return 修改后的结果
     * @author 刘梦娇
     * @since 2.0.0 2018-12-14 15:01:12
     */
    @Override
    public boolean modifyJudgeTask(JudgeTaskModel judgeTaskModel) {

        JudgeTaskModelNorequired judgeTaskModelNorequired = new JudgeTaskModelNorequired();
        JudgeTaskEntity judgeTaskEntity = new JudgeTaskEntity();
        BeanUtils.copyProperties(judgeTaskModel, judgeTaskEntity);
//        judgeTaskModelNorequired.setExaminationId(judgeTaskModel);
//        return judgeTaskDao.modifyJudgeTask(id, teacherId);
        return this.updateById(judgeTaskEntity);
    }

    /**
     * 添加判分任务到JudgeTask
     *
     * @param judgeTaskModel JudgeTaskEntity
     * @return 添加判分任务
     * @author 杨海云
     * @since 2.0.0 2018-12-12 21:33:10
     */
    @Override
    public boolean insertJudgeTask(JudgeTaskModel judgeTaskModel) {
        List<JudgeTaskModel> judgeTaskModelList = judgeTaskDao.queryExistJudgeTask(judgeTaskModel.getExaminationId(), judgeTaskModel.getTemplateDetailsId(), judgeTaskModel.getTeachclassId());
        JudgeTaskEntity judgeTaskEntity = new JudgeTaskEntity();
        BeanUtils.copyProperties(judgeTaskModel, judgeTaskEntity);
        if (judgeTaskModelList.size() == 0) {
            return this.save(judgeTaskEntity);
        } else {
            return false;
        }
    }

    /**
     * 查询是否存在JudgeTask
     *
     * @param examinationId    考试id
     * @param templateDetilsId 题型名称id
     * @param teachClassId     批卷班级id
     * @return 查询是否存在 JudgeTask
     * @author 杨海云
     * @since 2.0.0 2018-12-12 21:33:10
     */
    @Override
    public List<JudgeTaskModel> queryExistJudgeTask(String examinationId, String templateDetilsId, String teachClassId) {

        return judgeTaskDao.queryExistJudgeTask(examinationId, templateDetilsId, teachClassId);
    }


    /**
     * 组合查询，根据考试id，题型id，批卷班级id，批卷教师id
     *
     * @param operator          操作人
     * @param examinationId     考试id
     * @param templateDetailsId 题型id
     * @param teachclassId      批卷班级id
     * @param teacherId         批卷教师id
     * @param pageNo            分页页数
     * @param pageSize          分页大小
     * @return 符合条件的判分任务
     * @author 刘梦娇
     * @since 2018-12-18 19:45:21
     */
    @Override
    public PageInfo<JudgeTaskModelResult> queryCombine(String operator, String examinationId, String templateDetailsId, String teachclassId, String teacherId, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(judgeTaskDao.queryCombine(operator, examinationId, templateDetailsId, teachclassId, teacherId));

    }

    @Override
    public boolean updateExamtionState(String examtionId) {
        ExaminationEntity examinationEntity = new ExaminationEntity();
        examinationEntity.setId(examtionId);
        examinationEntity.setState(3);
        return examinationService.updateById(examinationEntity);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean importJson(File file) throws IOException {
        String[] list = file.list();
        if (list==null||list.length<=0){
            log.warn("没有文件需要导入!!!");
            return false;
        }
        log.info("一共{}个文件需要导入",list.length);
        for (String s : list) {
            log.info("{}文件开始导入!!!",s);
            File f = new File(file.getPath() + "\\" + s);
            FileInputStream fileInputStream = new FileInputStream(f);
//        InputStream inputStream1 = multipartFile.getInputStream();
            int available = fileInputStream.available();
            byte[] bbb = new byte[available];
            fileInputStream.read(bbb);
            String aaa = new String(bbb, "UTF-8");

            if (aaa.equals("[]")) {
                log.warn("该文件为空！！！{}", s);
                continue;
            }

            List<ImportJson> importJsons;
            try {
                importJsons = JacksonJsonUntil.jsonToList(aaa, ImportJson.class);
            } catch (Exception ex) {
                log.error("导入Json出错了！", ex);
                return false;
            }
            fileInputStream.close();
            if (importJsons != null && importJsons.size() > 0) {
                for (ImportJson importJson : importJsons) {
                    PaperRecordEntity paperRecordEntity = new PaperRecordEntity();
                    if (importJson.getPaperId() != null) {
                        paperRecordEntity.setId(importJson.getPaperId());
                    } else if (importJson.getPaperRecordId() != null) {
                        paperRecordEntity.setId(importJson.getPaperRecordId());
                    } else {
                        log.warn("该文件没有PaperId！{}", s);
                        continue;
                    }
                    //保存学生答案
                    StringBuilder stuAnswer = new StringBuilder();
                    //多选、填空、填图、计算分析
                    if (importJson.getQuestionCode() == 2 || importJson.getQuestionCode() == 0 || importJson.getQuestionCode() == 19 || importJson.getQuestionCode() == 18 ) {
                        for (int i = 0; i < importJson.getStudentAnswerArray().length; i++) {
                            if (importJson.getStudentAnswerArray()[i] == null) {
                                stuAnswer.append("|");
                            } else {
                                stuAnswer.append(importJson.getStudentAnswerArray()[i]).append("|");
                            }
                        }
                        stuAnswer.substring(0, stuAnswer.length() - 1);
                        paperRecordEntity.setStudentAnswerArrayStr(stuAnswer.toString());
                        paperRecordService.updateById(paperRecordEntity);
                        log.info("该题型导入成功，题型Code为：{}", importJson.getQuestionCode());
                    } else {
                        stuAnswer.append(importJson.getStudentAnswerArray()[0]);
                        paperRecordEntity.setStudentAnswerArrayStr(stuAnswer.toString());
                        paperRecordService.updateById(paperRecordEntity);
                        log.info("该题型导入成功，题型Code为：{}", importJson.getQuestionCode());
                    }

                    //这两个是手动判分的题，简答、名词解释
                    if (importJson.getQuestionCode() != 11 || importJson.getQuestionCode() != 20) {
                        //调用自动判分
                        PaperOnlineRecordModel paperOnlineRecordModel = new PaperOnlineRecordModel();
                        if (importJson.getPaperId() != null) {
                            paperOnlineRecordModel.setPaperRecordId(importJson.getPaperId());
                        } else if (importJson.getPaperRecordId() != null) {
                            paperOnlineRecordModel.setPaperRecordId(importJson.getPaperRecordId());
                        }
                        paperOnlineRecordModel.setQuestionCode(importJson.getQuestionCode().toString());
                        paperOnlineRecordModel.setStudentAnswerS(stuAnswer.toString());
                        if (importJson.getQuestionCode()==16){
                            paperOnlineRecordModel.setStudentAnswerArray(importJson.getStudentAnswerArray());
                        }
                        paperOnlineRecordModel.setStandardScore(importJson.getStandardScore());
//                        paperOnlineRecordModel.setOptionCount(importJson.getStudentAnswerArray().length);
                        automaticJudge(paperOnlineRecordModel);
                    }
                }
            }
        }
        return true;
    }

    @Transactional(rollbackOn = Exception.class)
    @Override
    public boolean againJudge(String examtionId) {
        //通过考试ID查询本场考试所有学生
        ExamineeEntity examineeEntity = new ExamineeEntity();
        examineeEntity.setExaminationId(examtionId);
        Wrapper<ExamineeEntity> wrapper = new QueryWrapper<>(examineeEntity);
        List<ExamineeEntity> list = examineeService.list(wrapper);
        if (list == null || list.size() <= 0) {
            log.warn("该场考试下没有考生");
            return false;
        }
        int a = 0;
        for (ExamineeEntity examineeEntity1 : list) {
            a++;
            PaperRecordEntity paperRecordEntity = new PaperRecordEntity();
            paperRecordEntity.setExaminationId(examtionId);
            paperRecordEntity.setExamineeId(examineeEntity1.getId());
            Wrapper<PaperRecordEntity> wrapper1 = new QueryWrapper<>(paperRecordEntity);
            List<PaperRecordEntity> list1 = paperRecordService.list(wrapper1);
            if (list1 == null || list1.size() <= 0) {
                log.warn("该场考生没有答题记录，考生ID:{}，考试ID:{}", examineeEntity1.getId(), examtionId);
                continue;
            }
            String quesTypeId = "";
            String quesCode = "";
            int b = 0;
            for (PaperRecordEntity paperRecordEntity1 : list1) {
                b++;
                if (!StringUtils.isEmpty(paperRecordEntity1.getStudentAnswerArrayStr())) {
                    //调用自动判分
                    PaperOnlineRecordModel paperOnlineRecordModel = new PaperOnlineRecordModel();
                    paperOnlineRecordModel.setPaperRecordId(paperRecordEntity1.getId());
                    if (quesTypeId.equals("") || !quesTypeId.equals(paperOnlineRecordModel.getQuestionTypeId())) {
                        quesTypeId = paperRecordEntity1.getQuestionTypeId();
                        QuestionTypeEntity questionTypeEntity = questionTypeService.getById(quesTypeId);
                        quesCode = questionTypeEntity.getCode();
                    }
                    //业务题、简答题、名词解释不能调用自动判分
                    if (quesCode.equals("16") || quesCode.equals("11") || quesCode.equals("20")) {
                        log.info("业务题16、简答题11、名词解释20、不能自动判分，题型code：{}", quesCode);
                        continue;
                    }
                    paperOnlineRecordModel.setQuestionCode(quesCode);
                    paperOnlineRecordModel.setStudentAnswerS(paperRecordEntity1.getStudentAnswerArrayStr());
                    paperOnlineRecordModel.setStandardScore(paperRecordEntity1.getStandardScore());
                    paperOnlineRecordModel.setState(true);
                    automaticJudge(paperOnlineRecordModel);
                }
            }

        }
        return true;
    }

    @Override
    public boolean againJudgeQuesIsDelete(String examtionId) {
        PaperRecordEntity paperRecordEntity = new PaperRecordEntity();
        paperRecordEntity.setExaminationId(examtionId);
        paperRecordEntity.setMarkStatus(0);
//        paperRecordEntity.setStudentAnswerArrayStr("NOT_EMPTY");
        Wrapper<PaperRecordEntity> wrapper = new QueryWrapper<>(paperRecordEntity);
        ((QueryWrapper<PaperRecordEntity>) wrapper).isNotNull("student_answer_array_str");
        List<PaperRecordEntity> list = paperRecordService.list(wrapper);
        if (list != null && list.size() > 0) {
            String quesTypeId = "";
            String quesCode = "";
            for (PaperRecordEntity paperRecordEntity1 : list) {
                paperRecordEntity1.setMarkStatus(1);
                if (paperRecordEntity1.getCorrectAnswer().trim().equals(paperRecordEntity1.getStudentAnswerArrayStr().trim())) {
                    paperRecordEntity1.setScore(paperRecordEntity1.getStandardScore());
                } else {
                    paperRecordEntity1.setScore(0.0);
                }
                paperRecordService.updateById(paperRecordEntity1);
            }
        }
        return true;
    }

    @Transactional(rollbackOn = Exception.class)
    @Override
    public boolean againJudgeQuesIsDelete() {
//        PaperRecordEntity paperRecordEntity=new PaperRecordEntity();
//        PaperRecordEntity byId = paperRecordService.getById("1082427611931570190");
//        byId.setCorrectAnswer(byId.getCorrectAnswer().replaceAll("\n",""));
        Wrapper<PaperRecordEntity> wrapper = new QueryWrapper<>();
        ((QueryWrapper<PaperRecordEntity>) wrapper).ne("question_type_id", "1072112901400514567");
        // ((QueryWrapper<PaperRecordEntity>) wrapper).eq("question_type_id","1072112901400514561");
        ((QueryWrapper<PaperRecordEntity>) wrapper).like("student_answer_array_str", "<p>");
        List<PaperRecordEntity> list = paperRecordService.list(wrapper);
        for (PaperRecordEntity paperRecordEntity1 : list) {
            paperRecordEntity1.setStudentAnswerArrayStr(paperRecordEntity1.getStudentAnswerArrayStr().replaceAll("<p>", "").replaceAll("</p>", "").replaceAll("&nbsp;", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("<br/>", "").replaceAll("<br />", ""));
            paperRecordEntity1.setCorrectAnswer(paperRecordEntity1.getCorrectAnswer().replaceAll(" ", "").replaceAll("\n", ""));
            String studentAnswerArrayStr = paperRecordEntity1.getStudentAnswerArrayStr().replaceAll("<p>", "").replaceAll("</p>", "").replaceAll("&nbsp;", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\|", "").replaceAll("<br/>", "").replaceAll("<br />", "");
            String CorrectAnswer = paperRecordEntity1.getCorrectAnswer().replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\|", "");

            if (studentAnswerArrayStr.trim().equals(CorrectAnswer.trim())) {
                paperRecordEntity1.setScore(paperRecordEntity1.getStandardScore());
            }
            paperRecordService.updateById(paperRecordEntity1);
        }
        return true;
    }

    @Override
    public boolean againJudgeByBusiness() {
        List<ModifyScoreModel> modifyScoreModels = judgeTaskDao.againJudgeByBusiness();
        List<PaperRecordEntity>paperRecordEntities=new ArrayList<>();
        for (ModifyScoreModel modifyScoreModel:modifyScoreModels){
            PaperRecordEntity paperRecordEntity=new PaperRecordEntity();
            paperRecordEntity.setId(modifyScoreModel.getPaperRecordId());
            paperRecordEntity.setScore(modifyScoreModel.getTotalScore());
            paperRecordEntity.setStandardScore(modifyScoreModel.getQuestionScore());
            paperRecordEntities.add(paperRecordEntity);
        }
        paperRecordService.updateBatchById(paperRecordEntities);
        return true;
    }

    @Override
//    todo  程金鹏成绩汇总1
    public boolean totalScoreManyThread(List<TotalScoreModel> examineeModelList) {
        if (examineeModelList==null||examineeModelList.size()<=0){
            log.warn("参数传递失败，内容为空！！！");
            return false;
        }
        ThreadPoolExecutor executor=new ThreadPoolExecutor(10, 200, 60000, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>());

        for (TotalScoreModel totalScoreModel:examineeModelList){
            TotalScore totalScore=new TotalScore();
            totalScore.setExamtionId(totalScoreModel.getExaminationId());
            totalScore.setExamClassId(totalScoreModel.getClassId());
            totalScore.setJudgeTaskService(this);
            executor.execute(totalScore);
            log.info("线程池中线程数目："+executor.getPoolSize()+"，队列中等待执行的任务数目："+
                    executor.getQueue().size()+"，已执行玩别的任务数目："+executor.getCompletedTaskCount());
        }
        executor.shutdown();
        return true;
    }

}
